package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.JobInfoAdapter;
import com.yzx.lifeassistants.adapter.MyPoupWindowAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.JobInfo;
import com.yzx.lifeassistants.model.IQueryJob;
import com.yzx.lifeassistants.model.callback.IQueryJobCB;
import com.yzx.lifeassistants.model.impl.QueryJobImpl;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 招聘资讯
 * @author: yzx
 * @time: 2016-3-7 下午1:27:01
 */
@SuppressLint("InflateParams")
public class JobActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener {

	private ImageButton backBtn;// 返回按钮
	private TextView typeTV;// 类型
	private ListView jobLV;// 讲座列表
	private PullToRefreshListView jobPTRLV;// 刷新
	private ILoadingLayout jobILL;// 加载

	private CircularLoadingDialog dialog;// 加载
	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 加载更多
	private int curPage = 0; // 当前页的编号，从0开始
	private int loadType;// 加载类型
	private List<JobInfo> dataList;// 招聘信息列表
	private JobInfoAdapter adapter;// 招聘信息列表适配器
	private Handler handler;//
	private IQueryJobCB queryCallBack;// 查询回调
	private IQueryJob queryJob;// 查询
	private PopupWindow popupWindow;// 类型选择框
	private int type = 0;// 类型

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_job);
		initView();
		setListener();
		initPoupWindow();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.job_back_btn);
		typeTV = (TextView) findViewById(R.id.job_type_tv);
		jobPTRLV = (PullToRefreshListView) findViewById(R.id.job_listview);
		jobILL = jobPTRLV.getLoadingLayoutProxy();
		jobILL.setLastUpdatedLabel("");
		jobILL.setPullLabel("继续拖动");
		jobILL.setRefreshingLabel("正在装载数据···");
		jobILL.setReleaseLabel("放开装载更多");
		jobLV = jobPTRLV.getRefreshableView();
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		typeTV.setOnClickListener(this);
		// 滑动监听
		jobPTRLV.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem == 0) {
					jobILL.setLastUpdatedLabel("");
					jobILL.setPullLabel("下拉刷新");
					jobILL.setRefreshingLabel("加载中···");
					jobILL.setReleaseLabel("释放刷新");
				} else if (firstVisibleItem + visibleItemCount == totalItemCount) {
					jobILL.setLastUpdatedLabel("");
					jobILL.setPullLabel("继续拖动");
					jobILL.setRefreshingLabel("正在装载数据···");
					jobILL.setReleaseLabel("放开装载更多");
				}
			}
		});
		// 下拉刷新监听
		jobPTRLV.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 下拉刷新(从第一页开始装载数据)
				queryJob(0, STATE_REFRESH);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 上拉加载更多(加载下一页数据)
				queryJob(curPage, STATE_MORE);
			}

		});
		jobLV.setOnItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化PoupWindow弹框
	 */
	@SuppressWarnings("deprecation")
	private void initPoupWindow() {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.poupwindow, null);
		ListView groupLV = (ListView) view.findViewById(R.id.poupwindow_lv);
		// 加载数据
		List<String> groupList = new ArrayList<String>();
		groupList.add("专场招聘会");
		groupList.add("周末招聘会");
		groupList.add("大型招聘会");
		MyPoupWindowAdapter groupAdapter = new MyPoupWindowAdapter(this,
				groupList);
		groupLV.setAdapter(groupAdapter);
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 创建一个PopuWidow对象
		popupWindow = new PopupWindow(view, windowManager.getDefaultDisplay()
				.getWidth() / 2,
				windowManager.getDefaultDisplay().getHeight() / 3);
		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		groupLV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long arg3) {
				type = position;
				if (0 == position) {
					typeTV.setText("专场招聘会");
				} else if (1 == position) {
					typeTV.setText("周末招聘会");
				} else if (2 == position) {
					typeTV.setText("大型招聘会");
				}
				queryJob(0, STATE_REFRESH);// 查询
				if (popupWindow != null) {
					popupWindow.dismiss();
				}
			}
		});
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		typeTV.setText("专场招聘会");
		dialog = new CircularLoadingDialog(this);
		dataList = new ArrayList<JobInfo>();
		adapter = new JobInfoAdapter(this, dataList);
		SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
				adapter);
		swingBottomInAnimationAdapter.setAbsListView(jobLV);
		jobLV.setAdapter(swingBottomInAnimationAdapter);

		handler = new Handler();
		queryCallBack = new IQueryJobCB() {

			@Override
			public void querySuccess(final List<JobInfo> lectures) {
				handler.post(new Runnable() {

					@Override
					public void run() {// 查询成功
						dialog.dismiss();
						if (STATE_REFRESH == loadType) {
							dataList.clear();
							curPage = 0;
						}
						dataList.addAll(lectures);
						curPage++;
						jobPTRLV.onRefreshComplete();
						adapter.notifyDataSetChanged();
					}
				});
			}

			@Override
			public void queryError(final int code) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						switch (code) {
						case IQueryJobCB.RESULR_NULL: {// 暂无更多
							String typeString = typeTV.getText().toString();
							if (STATE_MORE == loadType) {
								showToast("暂时还未有更多的" + typeString + "信息~", true);
							}
							if (STATE_REFRESH == loadType) {
								showToast("暂时还未有" + typeString + "信息~", true);
							}
							break;
						}
						case IQueryJobCB.QUERY_ERROR: {// 获取失败
							showToast("获取失败，请确认网络连接后刷新重试~", false);
							break;
						}
						default:
							break;
						}
						dialog.dismiss();
						jobPTRLV.onRefreshComplete();
						adapter.notifyDataSetChanged();
					}

				});
			}

		};
		queryJob = new QueryJobImpl(this, queryCallBack);
		queryJob(0, STATE_REFRESH);
	}

	/**
	 * 
	 * @Description: 查询招聘信息
	 */
	private void queryJob(int curPage, int actionType) {
		loadType = actionType;
		dialog.show();
		queryJob.queryJob(curPage + 1, 3 - type);
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.job_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.job_type_tv: {// 选择类别
			popupWindow.showAsDropDown(v,
					-typeTV.getWidth() + DensityUtils.dp2px(this, 20)
							+ DensityUtils.sp2px(this, 76), 0);
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 列表按键监听
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		Intent intent = new Intent(this, JobInfoActivity.class);
		intent.putExtra("JOB_INFO_URL", dataList.get(position - 1).getUrl());
		startActivity(intent);
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.job_top_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.job_top_ll);
		}

	}
}
